<!-- 新增房间 -->
<template>
   <div class="container">
      <el-page-header @back="goBack" content="房间管理" style="padding-bottom:20px"></el-page-header>
      <el-form
         ref="form"
         :model="form"
         :rules="rules"
         label-position="left"
         label-width="100px"
      >
         <el-form-item label="房间名称:" prop="roomName">
            <el-col :span="11">
               <el-input v-model="form.roomName" />
            </el-col>
         </el-form-item>

         <el-form-item label="房间位置:" prop="roomSite">
            <el-col :span="11">
               <el-input v-model="form.roomSite" />
            </el-col>
         </el-form-item>
         <el-form-item label="房间类型:" prop="roomType">
            <el-select v-model="form.roomType" placeholder="请选择" :filter-method="search">
               <el-option label="自理" value="0" />
               <el-option label="非自理" value="1" />
               <el-option label="混合" value="2" />
            </el-select>
         </el-form-item>
      </el-form>
      
      
      <!-- 床位列表 -->
      <div class="listTop">
         <div>床位列表</div>
         <vxe-button status="primary" @click="insertEvent(-1)">在最后行插入</vxe-button>
      </div>
      <vxe-table
         border
         show-overflow
         auto-resize
         ref="xTable"
         class="my_table_insert"
         max-height="400"
         :data="tableData"
         :edit-config="{trigger: 'click', mode: 'cell', icon: 'fa fa-pencil' , activeMethod:activeCellMethod}"
         @edit-disabled="editDisabledEvent">
         <!-- <vxe-table-column type="checkbox" width="60"></vxe-table-column> -->
         <vxe-table-column type="seq" width="60" title="序号"></vxe-table-column>
         <vxe-table-column field="name" title="床位名称" sortable :edit-render="{name: 'input'}"></vxe-table-column>
         <vxe-table-column field="bedState" title="床位状态" :edit-render="{name: '$select', options: bedState ,optionProps: {value: 'value', label: 'spell'} } ">
         </vxe-table-column>
         <vxe-table-column field="devCode" title="设备编号"  :edit-render="{name: 'input'}"></vxe-table-column>
         <vxe-table-column field="tenement" title="入住人姓名" :edit-render="{name: 'input'}"></vxe-table-column>
         <vxe-table-column field="tenementState" title="入住人状态" :edit-render="{name: '$select', options: tenementState ,optionProps: {value: 'value', label: 'spell'} } "></vxe-table-column>

         <vxe-table-column title="操作" width="250">
            <template v-slot="{ row }">
              <vxe-button type="text" style="color:#409EEE" icon="fa fa-edit" @click="handleEdit(row)">安排老人</vxe-button>
              <vxe-button type="text" style="color:#409EEE" icon="fa fa-edit" @click="handleUnbind(row)">解绑老人</vxe-button>
              <vxe-button type="text" style="color:#f56c6c" icon="el-icon-delete" @click="removeEvent(row)">删除</vxe-button>
            </template>
          </vxe-table-column>
      </vxe-table>

      <div class="submitBox">
         <el-button type="primary" @click="submitForm('form')">提  交</el-button>
      </div>

      <!-- 分配老人弹框 -->
      <el-dialog
         title=""
         :visible.sync="centerDialogVisible"
         width="40%"
      >
         <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-position="left"
            label-width="80px"
         >
            <div style="margin-bottom: 10px">
               快速分配：（以下是当前全院尚未分配床位的老人）
            </div>
            <!-- <el-form-item  prop="type"> -->
            
            <el-radio-group v-model="ruleForm.oldman" >
               <el-radio
                  @change='selectOldMan(item)'
                  v-for="(item, index) in list"
                  :key="index"
                  :label="item.name"
               ></el-radio>
            </el-radio-group>
         
            <div style="display:flex;padding-top:20px;">
               <div>确认老人参数：</div>
              <div style="color:#2dc">{{ ruleForm.datas.name }}（{{ ruleForm.datas.status == 0 ? '在院':'请假' }}，{{ bedData.name }}）</div>
            </div>
            <div class="submitBox">
               <el-button type="primary" @click="onSubmit" size="mini">确认分配</el-button>
            </div>
         </el-form>
      </el-dialog>
   </div>
</template>

<script>
import { addRoom , getUndistributed , bindingBed , untieElder } from "@/api/user";
export default {
   components: {},
   data() {
      return {
         centerDialogVisible: false,
         form: {
            roomName: "",
            roomSite: "",
            roomType: "",
         },
         list: [],   //快速分配老人列表
         ruleForm: {
            oldman: '',
             datas:'',
            search:'',
         },
         submitTag:false, //是否提交
         bedIndex:'',//床位列表index
         bedData:{}, //床位数据
         bedState: [
            // { spell: '', value: '' },
            { spell: '正常', value: '0' },
            { spell: '故障', value: '1' }
         ],
         tenementState:[
            { spell: '在院', value: '0' },
            { spell: '请假', value: '1' },
         ],
         tableData: [],//床位列表
         oldManList:[],//分配后的老人列表
         rules: {
            roomName: [{ required: true, message: '请输入房间名', trigger: 'blur' }],
            roomSite:[{required: true, message: '请输入房间位置', trigger: 'blur'}],
            roomType:[{required: true, message: '请选择房间类型', trigger: 'change'}],
         },
      };
   },
   methods: {
      goBack(){
         this.$router.push({ name: "roomManagement" });
      },
      search() {
         console.log(this.ruleForm.search);
      },
      selectOldMan(res){
         this.ruleForm.datas = res;
         // console.log(res)
      },
      //插入
      async insertEvent (row) {
         let record = {
            // sex: '1'
         }
         let { row: newRow } = await this.$refs.xTable.insertAt(record, row)
         await this.$refs.xTable.setActiveCell(newRow, 'name')
      },
      submitForm(formName) {
         this.oldManList = [];
         let submitFlag = false;
         let temArr = this.$refs.xTable.getInsertRecords()
         //遍历表格数据，整理数据以便提交
         if(temArr.length != 0){
            temArr.map((item)=>{
               this.oldManList.push({
                  devCode:item.devCode,
                  elderId:item.elderId ? item.elderId : '',
                  status:item.bedState,
                  name:item.name
               })
            })  
         }
          

         //存在新增数组 过滤 如果设备码，床位名，状态 一项为空不允许提交   不存在新列表也允许提交
         if(temArr.length != 0){
            this.oldManList.filter(item=>{
               if(!item.devCode || !item.name || !item.status){
                  this.$message({ message:'请完善，床位名称，床位状态和设备编号信息' })
               }else{
                   submitFlag = true;
               }
            })
         }else{
            submitFlag = true;
         }
         
         this.$refs[formName].validate((valid) => {
            console.log(valid && submitFlag)
            if (valid && submitFlag) {
               this.tableData = this.$refs.xTable.editStore.insertList
               addRoom(
                  this.form.roomName,
                  this.form.roomSite,
                  this.form.roomType,
                  this.oldManList
               ).then(res=>{
                  if(res.code == 2000){
                     this.$message('添加成功')
                     this.$router.push({ name: "roomManagement" });
                     this.submitTag = true;
                  }
               })
              
            } else {
               console.log('error submit!!')
               return false
            }
         })
      },
      //点击分配老人
      handleEdit(row) {
         console.log
         if(row.name && row.bedState){
            this.centerDialogVisible = true;
            this.bedData = row;
            // console.log(this.bedData)
            getUndistributed().then(res=>{
               this.list = res.data.elders;
               // console.log(res)
            })
         }else{
            this.$message({ message: '请填写床位名称和状态'});
         }
      },
      //解绑老人
      handleUnbind(row){
         
         untieElder(
            row.elderId
         ).then(res=>{
            if(res.code == 2000){
               // this.$message({
               //    message: '解绑成功',
               //    type: 'success'
               // });
               let temArr = this.$refs.xTable.getInsertRecords()
               temArr.filter(item =>{
                  if(item.elderId == row.elderId) {
                     item.tenement = ''
                     item.tenementState = ''
                     item.elderId =  '' 
                  }
               })
            }
         })

      },
      //分配老人
      onSubmit(){
         // console.log(this.ruleForm.datas)
         bindingBed(
            this.ruleForm.datas.id
         ).then(res=>{
            if( res.code == 2000 ){
              
              let temArr = this.$refs.xTable.getInsertRecords()

               //把老人信息录入表格
               temArr.filter(item =>{
                  if(item.name == this.bedData.name) {
                     item.tenement = this.ruleForm.datas.name
                     item.tenementState = this.ruleForm.datas.status
                     item.elderId =  this.ruleForm.datas.id 
                  }
               })

               // console.log(this.$refs.xTable.getData())
               // console.log(this.$refs.xTable.getInsertRecords())
               console.log(this.oldManList)

               this.centerDialogVisible = false;
               this.$message({
                  message: '分配成功',
                  type: 'success'
               });
            }
         })
      },

      removeEvent (row) {
         this.$XModal.confirm('您确定要删除该数据?').then(type => {
            if (type === 'confirm') {
               this.$refs.xTable.remove(row)
               
            }
         })
      },
      activeCellMethod ({ column, columnIndex }) {
         if (columnIndex === 4 || columnIndex === 5 ) {
            return false
         }
         return true
      },
      editDisabledEvent ({ row, column }) {
          this.$message({
          message: '警告,禁止编辑',
          type: 'warning'
        });
      },
      
   },
   computed: {},
   watch: {},
   created() {
      
   },
   mounted() {},
   beforeDestroy(){
      if(this.submitTag == false){
         let arr = [];
         let temArr = this.$refs.xTable.getInsertRecords()
         temArr.filter(item =>{
            if(item.elderId) {
               arr.push(item.elderId)
            }
         })
         arr = arr.join(',')
         
            untieElder(
               arr
            ).then(res=>{
               if(res.code == 2000){
                  // this.$message({
                  //    message: '解绑成功',
                  //    type: 'success'
                  // });
                  
               }
            })
         }
   }
};
</script>
<style lang='scss' scoped>

.container {
   padding: 20px;
   .submitBox{
      margin-top: 14px;
     display: flex;
     justify-content: center;
   }
   .listTop {
      font-size: 16px;
      color: #666;
      display: flex;
      justify-content: space-between;
      padding-bottom: 10px;
   }
}
</style>
